#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
"""
    ***********************************
    *  @filename : dash.py
    *  @Author : wshu
    *  @CodeDate : 2020/3/8 22:37
    *  @Software : PyCharm
    ***********************************
"""
import datetime
from core import BaseHandlers
from db.mysql import User
from db.mysql import Strategy
from core.auth.hashers import check_password
from core.comm.utils.timezone import now as timezone
import tornado.web
import tornado.gen
import tornado.escape

class MainHandler(BaseHandlers):
    """
    当前用户是否已登录
    """
    @tornado.web.authenticated  # 需要身份认证
    # @tornado.web.asynchronous # 6.0版本已弃用
    @tornado.gen.coroutine
    def get(self, *args, **kwargs):
        name = tornado.escape.xhtml_escape(self.current_user)
        # self.write('ok, ' + name)
        self.redirect('/dashboard')
        raise tornado.web.Finish

    def post(self, *args, **kwargs):
        self.write('ok')
        self.finish()
        raise tornado.web.Finish

class IndexHandler(BaseHandlers):
    """
    首页
    """
    error_msg = ''


    def get(self, *args, **kwargs):
        all_strategy_list = self.db.query(Strategy).all()
        self.render('main/index.html', error_msg=self.error_msg,
                    all_strategy_list=all_strategy_list)



class SignInHandler(BaseHandlers):
    """
    登录
    password: sadew@233###
    """
    error_msg = ''

    def get(self, *args, **kwargs):
        self.render('main/login.html', state=self.error_msg)

    def post(self, *args, **kwargs):
        username = self.get_argument('username')
        password = self.get_argument('password')
        _xsrf = self.get_argument('_xsrf', None)
        # print("xsrf token: ", _xsrf)
        user_get = self.db.query(User).filter_by(username=username).first()
        if user_get:
            stroed_password = user_get.password
            if user_get.lock_time > timezone():
                self.error_msg = u'账号已锁定,' + str(user_get.lock_time.strftime("%Y-%m-%d %H:%M")) + '后尝试重新登录'
            else:
                user = check_password(stroed_password, password)
                if user_get.is_active:
                    if user:
                        user_get.error_count = 0
                        # login succed
                        self.set_secure_cookie("user", username, expires_days=1)
                        self.redirect('/dashboard')
                        raise tornado.web.Finish
                    else:
                        user_get.error_count += 1
                        if user_get.error_count > 5:
                            user_get.error_count = 0
                            user_get.lock_time = timezone() + datetime.timedelta(minutes=6)
                        # 插入数据, 更新锁定时间
                        self.error_msg = '登录失败，累计错误登录' + str(user_get.error_count) + '次，5次后账号锁定'
                else:
                    self.error_msg = '登录失败，用户未激活'
        else:
            self.error_msg = '用户不存在，请检查用户是否有效'
        self.render('main/login.html', state=self.error_msg)


class LogoutHandler(BaseHandlers):
    """
    登出
    """
    def get(self, *args, **kwargs):
        self.clear_cookie('user')
        self.redirect(self.get_argument('next', '/'))

class DashboardHandler(BaseHandlers):
    """
    仪表盘
    """
    @tornado.web.authenticated
    # @tornado.web.asynchronous # 6.0版本已弃用
    @tornado.gen.coroutine
    def get(self, *args, **kwargs):
        user = self.get_current_user()
        if not user:
            self.redirect('/signin')
        self.render('dashboard.html')
        raise tornado.web.Finish

    def post(self, *args, **kwargs):
        self.write('ok')
        self.finish()


class ArticleViewHandler(BaseHandlers):
    """
    知识共享
    """
    def get(self, *args, **kwargs):
        self.render('main/articel_list.html')


class ArticleUpdateHandler(BaseHandlers):
    """
    知识库更新
    """
    def post(self, *args, **kwargs):
        self.write('ok')